package com.im.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.im.entity.ImGroup;
import com.im.entity.ImGroupMember;
import com.im.entity.ImUser;
import com.im.entity.vo.GroupVO;
import com.im.exception.GlobalException;
import com.im.mapper.ImGroupMapper;
import com.im.service.IImGroupMemberService;
import com.im.service.IImGroupService;
import com.im.service.IImUserService;
import com.im.session.SessionContext;
import com.im.session.UserSession;
import com.im.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 *  群聊服务操作类
 * </p>
 *
 * @author XainSir
 * @since 2025-01-30
 */
@Service
@Slf4j
public class ImGroupServiceImpl extends ServiceImpl<ImGroupMapper, ImGroup> implements IImGroupService {

    private Long userId;
    @Autowired
    private IImUserService userService;
    @Autowired
    private IImGroupMemberService groupMemberService;

    @Override
    public GroupVO createGroup(GroupVO vo) {
        //获取Session中用户信息即为群聊创建者
        UserSession session = SessionContext.getSession();

        if(session!=null) userId=session.getUserId();
        else userId=1887490632320278530L;

        ImUser user = userService.getById(userId);

        //创建群聊并且加入DB
        ImGroup group = BeanUtils.copyProperties(vo,ImGroup.class);
        group.setOwnerId(user.getId());
        this.save(group);

        //将群主加入群聊中,将群聊对象加入DB
        ImGroupMember member = new ImGroupMember()
                .setGroupId(group.getGroupId())
                .setUserId(user.getId())
                .setRole(2);
        groupMemberService.save(member);

        //设置GroupId的属性并且返回
        vo.setGroupId(group.getId());
        log.info("group_create✅_id:{}_name:{}",group.getId(),group.getName());
        return vo;
    }

    @CacheEvict(key = "#vo.getId()")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public GroupVO modifyGroup(GroupVO vo) {
        //获取Session中用户信息即为群聊创建者
        UserSession session = SessionContext.getSession();
        if(session!=null) userId=session.getUserId();
        else userId=1887490632320278530L;

        //校验资格，只有群主有资格修改信息
        ImGroup group = this.getAndCheckById(vo.getGroupId());
        // 更新成员信息

        // 群主有权修改群基本信息
        if (group.getOwnerId().equals(userId)) {
            group = BeanUtils.copyProperties(vo, ImGroup.class);
            this.updateById(group);
        }
        log.info("group_update✅，id:{}_name:{}", group.getId(), group.getName());
        return vo;
    }

    @Cacheable(key = "#groupId")
    @Override
    public ImGroup getAndCheckById(Long groupId) {
        ImGroup group = super.getById(groupId);
        if(Objects.isNull(group))throw new GlobalException("群组不存在");
        //群组已解散
        //群主已封禁，原因xxx
        return group;
    }

}
